class Admins::JifengerensController < ApplicationController
  def index
  
     t = Time.now.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S")
    t1 = Time.mktime(Time.now.year,1,1).beginning_of_day.strftime("%Y-%m-%d %H:%M:%S")
   
    
    session[:news_begin] = params[:news_begin] ? params[:news_begin].to_date.beginning_of_day.strftime("%Y-%m-%d %H:%M:%S") : t1
    session[:news_end] = params[:news_end] ? params[:news_end].to_date.at_end_of_day.strftime("%Y-%m-%d %H:%M:%S") : t

    departments = Department.where("short_name is not null ")
    @tongj  =   Array.new(departments.size()) { Hash.new }
    departments.each_with_index  do |department,i|
      p i.to_s  + department.name.to_s
      @tongj[i]["department"] =  department.name.to_s
    end

    #上传
    sql = "SELECT contribution_units,count(1) as \"check\" from news WHERE 1=1 and pubtime >='"+session[:news_begin] +"' and pubtime <= '"+session[:news_end]+"' GROUP BY contribution_units "
    @result = ActiveRecord::Base.connection.execute(sql)
    #采用
    sql = "SELECT contribution_units,count(1) as  check  from news n ,news_groups  g WHERE n.\"id\" = g.news_id and g.\"check\" = 1 and g.group_id = 15  and n.pubtime >='"+session[:news_begin] +"' and n.pubtime <= '"+session[:news_end]+"'  GROUP BY contribution_units ; "
    @result2 = ActiveRecord::Base.connection.execute(sql)

    @tongj.each do| tongfji|
      tongfji["sc"] = 0
      tongfji["cy"] = 0
      tongfji["cyl"] = 0
      tongfji["scp"] = 0
      tongfji["cylp"] = 0

      @result.each do |xw|
        if tongfji["department"] == xw["contribution_units"]
          tongfji["sc"] = xw["check"].to_i
        end
      end
      @result2.each do |xw|
        if tongfji["department"] == xw["contribution_units"]
          tongfji["cy"] = xw["check"].to_i
        end
      end

      tongfji["cyl"] =  tongfji["cy"]*100/ tongfji["sc"] if tongfji["sc"]!=0
      tongfji["cyl"]  = format('%.2f',tongfji["cyl"] ).to_i

    end

    @tongj = @tongj.sort_by {|u| u["cyl"]}
    @tongj.each_with_index do |tongfji, i|
      tongfji["cylp"] = @tongj.size()-i
    end
    @tongj = @tongj.sort_by {|u| u["sc"]}
    @tongj.each_with_index do |tongfji, i|
      tongfji["scp"] = @tongj.size()-i
    end

  end
end
